﻿using System;
using System.Windows;
using System.Collections.Generic;
using Baosight.Platform.Core.UI.Controls;
using Baosight.ZNH.ZMCA.UI.Utils;
using Telerik.Windows.Controls.Charting;
using Telerik.Windows.Controls;
using Baosight.Platform.Core;
using Baosight.Platform.Core.ServiceModel;
using Baosight.ZNH.ZMCA.UI.Controls;
using System.Reflection;
using Baosight.ZNH.ZMCA.UI.Model;


namespace Baosight.ZNH.ZMCA.UI
{


    public partial class ZMCA12 : EFView
    {
        ZMCA12Controler controler = new ZMCA12Controler();
        public ZMCA12()
        {
            InitializeComponent();
            FillGaugeData();
            FillChartData(this.chartLevel, this.chartClass);
            FillListViewData();

        }

        private void FillListViewData()
        {
            controler.GetListViewData(lstView);
        }

        private void FillGaugeData()
        {
            controler.GetGaugeData(gauge);
        }


        public void FillChartData(RadChart chartLevel, RadChart chartClass)
        {
            controler.GetRiskChartData(chartLevel, chartClass);
        }
    }

    public class ZMCA12Controler
    {
        DoubleCircleGauge gauge;
        RadChart chartLevel;
        RadChart chartClass;
        RadTreeListView lstView;
        public ZMCA12Controler()
        {
            
        }


        /// <summary>
        /// 调用服务ZMCA12.queryByIndex获得指标数据，然后填入指标盘
        /// </summary>
        /// <param name="gauge"></param>
        public void GetGaugeData(DoubleCircleGauge gauge)
        {
            this.gauge = gauge;
            gauge.gaugeTitle.Text = "安全隐患";
            gauge.leftGaugeDescription.Text = "待处理(个)";
            gauge.rightGaugeDescription.Text = "昨日(个)";

            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA12");
            eiInfo.Set("method", "queryByIndex");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, getGaugeDataCompleted);
        }

        private void getGaugeDataCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                Common.Alert(Common.MsgLoadDataError);
                return;
            }
            EIInfo eiInfo = e.EIInfo;
            EIBlock result = eiInfo.GetBlock("result");
            if (result != null && result.Rows.Count > 0)
            {
                foreach (var item in result.Rows)
                {
                    //年度数据的fdRiskDate长度为4，昨天数据的fdRiskDate长度为10（2011vs2011-05-05）
                    if (item["fdRiskDate"].ToString().Length == 4)
                    {
                        gauge.leftNeedle.Value = Common.GetIntValue(item["fdKeyId"]);
                    }
                    else
                    {
                        gauge.rightNeedle.Value = Common.GetIntValue(item["fdKeyId"]);
                    }
                }
            }

            gauge.leftControler.IsReverse = true;
            gauge.rightControler.IsReverse = true;
        }


        /// <summary>
        /// 调用服务ZMCA12.queryByChart获得趋势数据，然后填入趋势图
        /// </summary>
        /// <param name="chartLevel"></param>
        /// <param name="chartClass"></param>
        public void GetRiskChartData(RadChart chartLevel, RadChart chartClass)
        {
            this.chartLevel = chartLevel;
            this.chartClass = chartClass;

            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA12");
            eiInfo.Set("method", "queryByChart");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, getChartDataCompleted);
        }

        private void getChartDataCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                Common.Alert(Common.MsgLoadDataError);
                return;
            }

            EIInfo eiInfo = e.EIInfo;
            //查询结果包括三个block
            //queryByYear为总体各月和全年的数据
            //queryByYearLevel为不同级别在各月和全年的数据
            //queryByYearClassify为不同类别在各月和全年的数据
            EIBlock queryByYear = eiInfo.GetBlock("queryByYear");
            EIBlock queryByYearLevel = eiInfo.GetBlock("queryByYearLevel");
            EIBlock queryByYearClassify = eiInfo.GetBlock("queryByYearClassify");
            //获得服务器年月时间信息
            int currentMonth = Common.GetIntValue(eiInfo.Get("month"));
            int currentYear = Common.GetIntValue(eiInfo.Get("year"));

            //初始化安全隐患级别趋势分析图
            chartLevel.DefaultView.ChartTitle.Content = currentYear + "全矿安全隐患级别趋势分析";
            chartLevel.DefaultSeriesDefinition.ShowItemToolTips = true;
            chartLevel.DefaultSeriesDefinition.LegendDisplayMode = LegendDisplayMode.DataPointLabel;
            chartLevel.DefaultView.ChartLegend.Header = string.Empty;

            this.chartLevel.DefaultView.ChartTitle.FontSize = Common.FontsizeSetting + 2;
            this.chartLevel.DefaultView.ChartArea.FontSize = Common.FontsizeSetting;
            this.chartLevel.DefaultView.ChartLegend.FontSize = Common.FontsizeSetting - 2;

            chartLevel.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            chartLevel.DefaultView.ChartArea.AxisY.MinorGridLinesVisibility = Visibility.Visible;
            chartLevel.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Visible;

            //构造总体数据柱状图，该柱状图同时被级别趋势分析图和类别趋势分析图使用
            SeriesMapping sm1 = new SeriesMapping();
            BarSeriesDefinition totalBar = new BarSeriesDefinition();
            sm1.SeriesDefinition = totalBar;
            sm1.LegendLabel = "Bar Series";
            sm1.CollectionIndex = 0;
            sm1.LegendLabel = "隐患总数";

            sm1.SeriesDefinition.ShowItemLabels = false;
            sm1.SeriesDefinition.ShowItemToolTips = true;
            sm1.SeriesDefinition.ShowZeroValuesLabels = true;

            sm1.ItemMappings.Add(new ItemMapping("Date", DataPointMember.XCategory));
            sm1.ItemMappings.Add(new ItemMapping("DataValue", DataPointMember.YValue));
            sm1.SeriesDefinition.InteractivitySettings.HoverScope = InteractivityScope.Series;
            sm1.SeriesDefinition.InteractivitySettings.SelectionScope = InteractivityScope.Series;
            sm1.SeriesDefinition.InteractivitySettings.SelectionMode = ChartSelectionMode.Multiple;
            chartLevel.SeriesMappings.Add(sm1);

            chartClass.DefaultView.ChartTitle.Content = currentYear + "全矿安全隐患类别趋势分析";
            chartClass.DefaultSeriesDefinition.ShowItemToolTips = true;
            chartClass.DefaultSeriesDefinition.LegendDisplayMode = LegendDisplayMode.DataPointLabel;
            chartClass.DefaultView.ChartLegend.Header = string.Empty;


            this.chartClass.DefaultView.ChartTitle.FontSize = Common.FontsizeSetting + 2;
            this.chartClass.DefaultView.ChartArea.FontSize = Common.FontsizeSetting;
            this.chartClass.DefaultView.ChartLegend.FontSize = Common.FontsizeSetting - 2;

            chartClass.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            chartClass.DefaultView.ChartArea.AxisY.MinorGridLinesVisibility = Visibility.Visible;
            chartClass.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Visible;

            chartClass.SeriesMappings.Add(sm1);

            //初始化数据源
            List<List<ChartData>> chartLevelItemsSource = new List<List<ChartData>>();
            List<List<ChartData>> chartClassItemsSource = new List<List<ChartData>>();

            //根据queryByYear块构造总体数据totalList
            List<ChartData> totalList = new List<ChartData>();
            for (int i = 1; i <= currentMonth; i++)
			{
                totalList.Add(new ChartData(i + "月", 0));
			}
            foreach (var item in queryByYear.Rows)
            {
                string date = item["fdRiskDate"].ToString();
                if (date.Trim() == string.Empty)
                {
                    continue;
                }
                AddChartDate(item, date, totalList);
            }

            chartLevelItemsSource.Add(totalList);
            chartClassItemsSource.Add(totalList);
            //将级别数据加入到chartLevelItemsSource
            GetLevelData(queryByYearLevel, currentMonth, chartLevelItemsSource);
            //将类别数据加入到chartClassItemsSource
            GetClassData(queryByYearClassify, currentMonth, chartClassItemsSource);

            chartLevel.ItemsSource = chartLevelItemsSource;
            chartClass.ItemsSource = chartClassItemsSource;

        }

        /// <summary>
        /// 将类别数据加入到chartClassItemsSource
        /// 具体过程和GetLevelData完全一样
        /// </summary>
        /// <param name="queryByYearClassify"></param>
        /// <param name="currentMonth"></param>
        /// <param name="itemsSource"></param>
        private void GetClassData(EIBlock queryByYearClassify, int currentMonth, List<List<ChartData>> itemsSource)
        {
            Dictionary<string, int> dic = new Dictionary<string, int>();
            foreach (var item in queryByYearClassify.Rows)
            {
                string date = item["fdRiskDate"].ToString();
                if (date.Trim() == string.Empty)
                {
                    continue;
                }

                if (!dic.ContainsKey(Common.GetStringValue(item["fdRiskClassify"])))
                {
                    List<ChartData> levelList = new List<ChartData>();
                    for (int i = 1; i <= currentMonth; i++)
                    {
                        levelList.Add(new ChartData(i + "月", 0));
                    }
                    itemsSource.Add(levelList);
                    dic.Add(Common.GetStringValue(item["fdRiskClassify"]), itemsSource.Count - 1);

                    SeriesMapping sm2 = new SeriesMapping();
                    SplineSeriesDefinition d2 = new SplineSeriesDefinition();
                    sm2.SeriesDefinition = d2;
                    sm2.LegendLabel = Common.GetStringValue(item["fdRiskClassify"]);
                    sm2.CollectionIndex = itemsSource.Count - 1;

                    sm2.SeriesDefinition.ShowItemLabels = false;
                    sm2.SeriesDefinition.ShowItemToolTips = true;
                    sm2.SeriesDefinition.ShowZeroValuesLabels = true;

                    sm2.ItemMappings.Add(new ItemMapping("Date", DataPointMember.XCategory));
                    sm2.ItemMappings.Add(new ItemMapping("DataValue", DataPointMember.YValue));

                    sm2.SeriesDefinition.InteractivitySettings.HoverScope = InteractivityScope.Series;
                    sm2.SeriesDefinition.InteractivitySettings.SelectionScope = InteractivityScope.Series;
                    sm2.SeriesDefinition.InteractivitySettings.SelectionMode = ChartSelectionMode.Multiple;

                    chartClass.SeriesMappings.Add(sm2);
                }
                List<ChartData> tList = itemsSource[dic[Common.GetStringValue(item["fdRiskClassify"])]];

                AddChartDate(item, date, tList);
            }
        }

        /// <summary>
        /// 将级别数据加入到chartLevelItemsSource
        /// </summary>
        /// <param name="queryByYearLevel"></param>
        /// <param name="currentMonth"></param>
        /// <param name="itemsSource"></param>
        private void GetLevelData(EIBlock queryByYearLevel, int currentMonth, List<List<ChartData>> itemsSource)
        {
            //dic记录每个级别数据在itemsSource中的位置
            Dictionary<string, int> dic = new Dictionary<string, int>();
            foreach (var item in queryByYearLevel.Rows)
            {
                string date = item["fdRiskDate"].ToString();
                if (date.Trim() == string.Empty)
                {
                    continue;
                }


                if (!dic.ContainsKey(Common.GetStringValue(item["fdRiskLevel"])))
                {
                    //还没有遇到过该级别的数据，则构造该级别数据的List
                    List<ChartData> levelList = new List<ChartData>();
                    for (int i = 1; i <= currentMonth; i++)
                    {
                        levelList.Add(new ChartData(i + "月", 0));
                    }
                    itemsSource.Add(levelList);
                    dic.Add(Common.GetStringValue(item["fdRiskLevel"]), itemsSource.Count - 1);

                    SeriesMapping sm2 = new SeriesMapping();
                    SplineSeriesDefinition d2 = new SplineSeriesDefinition();
                    sm2.SeriesDefinition = d2;
                    sm2.LegendLabel = Common.GetStringValue(item["fdRiskLevel"]);
                    sm2.CollectionIndex = itemsSource.Count - 1;
                    sm2.SeriesDefinition.ShowItemLabels = false;
                    sm2.SeriesDefinition.ShowItemToolTips = true;
                    sm2.SeriesDefinition.ShowZeroValuesLabels = true;
                    sm2.ItemMappings.Add(new ItemMapping("Date", DataPointMember.XCategory));
                    sm2.ItemMappings.Add(new ItemMapping("DataValue", DataPointMember.YValue));
                    sm2.SeriesDefinition.InteractivitySettings.HoverScope = InteractivityScope.Series;
                    sm2.SeriesDefinition.InteractivitySettings.SelectionScope = InteractivityScope.Series;
                    sm2.SeriesDefinition.InteractivitySettings.SelectionMode = ChartSelectionMode.Multiple;

                    chartLevel.SeriesMappings.Add(sm2);
                }
                //找到遇到级别数据的List
                List<ChartData> tList = itemsSource[dic[Common.GetStringValue(item["fdRiskLevel"])]];
                //将数据加入到List中
                AddChartDate(item, date, tList);
            }
        }

        private static void AddChartDate(EIRow item, string date, List<ChartData> tList)
        {
            //date格式为yyyy-MM
            if (date[5] == '0')
            {
                date = date.Substring(6);
            }
            else
            {
                date = date.Substring(5);
            }
            if (Common.GetIntValue(date) - 1 < tList.Count)
            {
                tList[Common.GetIntValue(date) - 1].DataValue = Common.GetDecimalValue(item["fdKeyId"]);
            }
        }

        /// <summary>
        /// 调用服务ZMCA12.queryByListView获得列表数据，然后将数据填入列表控件中
        /// </summary>
        /// <param name="lstView"></param>
        public void GetListViewData(RadTreeListView lstView)
        {
            this.lstView = lstView;
            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA12");
            eiInfo.Set("method", "queryByListView");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, getListViewDataCompleted);
        }

        private void getListViewDataCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                Common.Alert(Common.MsgLoadDataError);
                return;
            }

            EIInfo eiInfo = e.EIInfo;
            //查询结果包含很多块:总体发现数、总体整改数
            EIBlock queryByYear = eiInfo.GetBlock("queryByYear");
            EIBlock queryByYearR = eiInfo.GetBlock("queryByYearR");
            //按地点汇总发现数、整改数
            EIBlock queryByPlace = eiInfo.GetBlock("queryByPlace");
            EIBlock queryByPlaceR = eiInfo.GetBlock("queryByPlaceR");
            //按单位汇总发现数、整改数
            EIBlock queryByDepartment = eiInfo.GetBlock("queryByDepartment");
            EIBlock queryByDepartmentR = eiInfo.GetBlock("queryByDepartmentR");
            //按级别汇总发现数、整改数
            EIBlock queryByListL = eiInfo.GetBlock("queryByListL");
            EIBlock queryByListLR = eiInfo.GetBlock("queryByListLR");
            //按类别汇总发现数、整改数
            EIBlock queryByListC = eiInfo.GetBlock("queryByListC");
            EIBlock queryByListCR = eiInfo.GetBlock("queryByListCR");

            int currentMonth = Common.GetIntValue(eiInfo.Get("month"));
            int currentYear = Common.GetIntValue(eiInfo.Get("year"));

            //将超过当前月的列隐藏
            for (int i = 12 - currentMonth+2; i > 2; i--)
            {
                var cl = lstView.Columns[i];
                cl.IsVisible = false;
            }

            List<ZMCA12DetailItem> itemsSource = new List<ZMCA12DetailItem>();

            //构造5个默认的汇总记录,这5个汇总节点数据应该是一样的
            ZMCA12DetailItem yearItem = new ZMCA12DetailItem();
            ZMCA12DetailItem yearPlaceItem = new ZMCA12DetailItem();
            ZMCA12DetailItem yearDepartmentItem = new ZMCA12DetailItem();
            ZMCA12DetailItem yearLevelItem = new ZMCA12DetailItem();
            ZMCA12DetailItem yearClassifyItem = new ZMCA12DetailItem();

            itemsSource.Add(yearItem);
            Type itemType = yearItem.GetType();
            yearItem.Name = "全矿";
            yearPlaceItem.Name = "所有地点";
            yearItem.Items.Add(yearPlaceItem);
            yearLevelItem.Name = "所有级别";
            yearItem.Items.Add(yearLevelItem);
            yearClassifyItem.Name = "所有类别";
            yearItem.Items.Add(yearClassifyItem);
            yearDepartmentItem.Name = "所有单位";
            yearItem.Items.Add(yearDepartmentItem);

            //将总体数据填入汇总记录
            SetYearTotalItem(queryByYear, yearItem, yearPlaceItem, yearLevelItem, yearClassifyItem, itemType, "M{0}");
            SetYearTotalItem(queryByYearR, yearItem, yearPlaceItem, yearLevelItem, yearClassifyItem, itemType, "M{0}_Revise");

            //生成地点汇总子记录
            AddPlaceChildItemByBlock(queryByPlace, queryByPlaceR, yearPlaceItem, itemType);
            //生成级别汇总子记录
            AddChildItemByBlock(queryByListL, queryByListLR, yearLevelItem, itemType, "fdRiskLevel");
            //生成类别汇总子记录
            AddChildItemByBlock(queryByListC, queryByListCR, yearClassifyItem, itemType, "fdRiskClassify");
            //生成单位汇总子记录
            AddDepartmentChildItemByBlock(queryByDepartment, queryByDepartmentR, yearDepartmentItem, itemType);

            lstView.ItemsSource = itemsSource;
        }

        private static void SetYearTotalItem(EIBlock queryByYear, 
            ZMCA12DetailItem yearItem, ZMCA12DetailItem yearPlaceItem, ZMCA12DetailItem yearLevelItem, ZMCA12DetailItem yearClassifyItem, 
            Type itemType, string FieldPrefix)
        {
            foreach (var item in queryByYear.Rows)
            {
                string date = item["fdRiskDate"].ToString();
                if (date.Trim() == string.Empty)
                {
                    continue;
                }

                //日数据长度为10，年数据长度为4，月数据长度为7
                if (date.Length == 10)
                {
                    yearItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    yearPlaceItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    yearLevelItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    yearClassifyItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    continue;
                }
                else if (date.Length == 4)
                {
                    if (FieldPrefix.Contains("Revise"))
                    {
                        yearItem.DependantTotalYear_Revise = Common.GetIntValue(item["fdKeyId"]);
                        yearPlaceItem.DependantTotalYear_Revise = Common.GetIntValue(item["fdKeyId"]);
                        yearLevelItem.DependantTotalYear_Revise = Common.GetIntValue(item["fdKeyId"]);
                        yearClassifyItem.DependantTotalYear_Revise = Common.GetIntValue(item["fdKeyId"]);
                    }
                    else
                    {
                        yearItem.DependantTotalYear = Common.GetIntValue(item["fdKeyId"]);
                        yearPlaceItem.DependantTotalYear = Common.GetIntValue(item["fdKeyId"]);
                        yearLevelItem.DependantTotalYear = Common.GetIntValue(item["fdKeyId"]);
                        yearClassifyItem.DependantTotalYear = Common.GetIntValue(item["fdKeyId"]);
                    }
                    continue;
                }

                date = GetMonthByDate(date);

                PropertyInfo pi = itemType.GetProperty(string.Format(FieldPrefix, date));
                pi.SetValue(yearItem, Common.GetIntValue(item["fdKeyId"]), null);

                pi.SetValue(yearPlaceItem, Common.GetIntValue(item["fdKeyId"]), null);
                pi.SetValue(yearLevelItem, Common.GetIntValue(item["fdKeyId"]), null);
                pi.SetValue(yearClassifyItem, Common.GetIntValue(item["fdKeyId"]), null);
            }
        }

        /// <summary>
        /// 过程类似AddPlaceChildItemByBlock
        /// </summary>
        /// <param name="block"></param>
        /// <param name="blockR"></param>
        /// <param name="parentDetailItem"></param>
        /// <param name="itemType"></param>
        /// <param name="columnName">区分数据的列</param>
        private void AddChildItemByBlock(EIBlock block, EIBlock blockR, ZMCA12DetailItem parentDetailItem, Type itemType, string columnName)
        {
            ZMCA12DetailItem detailItem = null;
            Dictionary<string, ZMCA12DetailItem> dic = new Dictionary<string, ZMCA12DetailItem>();
            foreach (var item in block.Rows)
            {
                string date = item["fdRiskDate"].ToString();
                if (date.Trim() == string.Empty)
                {
                    continue;
                }

                string itemName = Common.GetStringValue(item[columnName]);
                if (detailItem == null || detailItem.Name != itemName)
                {
                    detailItem = new ZMCA12DetailItem();
                    parentDetailItem.Items.Add(detailItem);
                    detailItem.Name = itemName;
                    dic.Add(itemName, detailItem);
                }

                if (date.Length == 10)
                {
                    detailItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    continue;
                }
                else if (date.Length == 4)
                {
                    detailItem.DependantTotalYear = Common.GetIntValue(item["fdKeyId"]);
                    continue;
                }
                date = GetMonthByDate(date);

                PropertyInfo pi = itemType.GetProperty("M" + date);
                pi.SetValue(detailItem, Common.GetIntValue(item["fdKeyId"]), null);
            }

            foreach (var item in blockR.Rows)
            {
                string date = item["fdRiskDate"].ToString();
                if (date.Trim() == string.Empty)
                {
                    continue;
                }

                string itemName = Common.GetStringValue(item[columnName]);
                detailItem = dic[itemName];


                if (date.Length == 4)
                {
                    detailItem.DependantTotalYear_Revise = Common.GetIntValue(item["fdKeyId"]);
                    continue;
                }
                date = GetMonthByDate(date);

                PropertyInfo pi_Revise = itemType.GetProperty("M" + date + "_Revise");
                pi_Revise.SetValue(detailItem, Common.GetIntValue(item["fdKeyId"]), null);
            }
        }

        /// <summary>
        /// 生成地点汇总子记录
        /// </summary>
        /// <param name="block"></param>
        /// <param name="blockR"></param>
        /// <param name="parentDetailItem"></param>
        /// <param name="itemType"></param>
        private void AddPlaceChildItemByBlock(EIBlock block, EIBlock blockR, ZMCA12DetailItem parentDetailItem, Type itemType)
        {
            ZMCA12DetailItem detailItem = null;
            Dictionary<string, ZMCA12DetailItem> dic = new Dictionary<string, ZMCA12DetailItem>();
            //1. 先构造记录并填入发现数。
            foreach (var item in block.Rows)
            {
                string date = item["fdRiskDate"].ToString();
                if (date.Trim() == string.Empty)
                {
                    continue;
                }
                //fdDepartmentId实际上保存的是工作面的Id，工作面Id作为区别数据的Id
                string itemUniqueName = Common.GetStringValue(item["fdDepartmentId"]);
                //如果碰到了新的工作面，则构造新的记录
                if (detailItem == null || detailItem.UniqueName != itemUniqueName)
                {
                    detailItem = new ZMCA12DetailItem();
                    parentDetailItem.Items.Add(detailItem);
                    detailItem.UniqueName = itemUniqueName;
                    detailItem.Name = Common.GetStringValue(item["fdRiskPlace"]);
                    dic.Add(itemUniqueName, detailItem);
                }

                //日数据长度为10，年数据长度为4，月数据长度为7
                if (date.Length == 10)
                {
                    detailItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    continue;
                }
                else if (date.Length == 4)
                {
                    detailItem.DependantTotalYear = Common.GetIntValue(item["fdKeyId"]);
                    continue;
                }
                date = GetMonthByDate(date);

                //通过反射将数据填入相应的月数据属性中
                PropertyInfo pi = itemType.GetProperty("M" + date);
                pi.SetValue(detailItem, Common.GetIntValue(item["fdKeyId"]), null);
            }

            //2. 填入整改数
            foreach (var item in blockR.Rows)
            {
                string date = item["fdRiskDate"].ToString();
                if (date.Trim() == string.Empty)
                {
                    continue;
                }
                //直接根据itemUniqueName找到第一步添加的记录
                string itemUniqueName = Common.GetStringValue(item["fdDepartmentId"]);
                detailItem = dic[itemUniqueName];

                if (date.Length == 4)
                {
                    detailItem.DependantTotalYear_Revise = Common.GetIntValue(item["fdKeyId"]);
                    continue;
                }
                date = GetMonthByDate(date);

                PropertyInfo pi_Revise = itemType.GetProperty("M" + date + "_Revise");
                pi_Revise.SetValue(detailItem, Common.GetIntValue(item["fdKeyId"]), null);
            }
        }

        private static string GetMonthByDate(string date)
        {
            if (date.Length == 10)
            {
                date = date.Substring(0,7);
            }
            if (date[5] == '0')
            {
                date = date.Substring(6);
            }
            else
            {
                date = date.Substring(5);
            }
            return date;
        }

        /// <summary>
        /// 生成单位汇总子记录
        /// </summary>
        /// <param name="block"></param>
        /// <param name="blockR"></param>
        /// <param name="parentDetailItem"></param>
        /// <param name="itemType"></param>
        private void AddDepartmentChildItemByBlock(EIBlock block, EIBlock blockR, ZMCA12DetailItem parentDetailItem, Type itemType)
        {
            //dic保存单位和自己录之间的关系
            Dictionary<string, ZMCA12DetailItem> dic = new Dictionary<string, ZMCA12DetailItem>();
            ZMCA12DetailItem detailItem = null;
            //1. 先构造记录并填入发现数。
            foreach (var item in block.Rows)
            {
                string date = Common.GetStringValue(item["fdRiskDate"]);
                if (item["fdRiskDate"] != null && date.Trim() == string.Empty)
                {
                    continue;
                }

                //fdDepartmentId为区别数据的Id
                string itemUniqueName = Common.GetStringValue(item["fdDepartmentId"]);
                //如果碰到新的单位则构造新的记录，并将该记录加入到dic中
                if (detailItem == null || detailItem.UniqueName != itemUniqueName)
                {
                    detailItem = new ZMCA12DetailItem();
                    dic.Add(itemUniqueName, detailItem);
                    //fdDepartmentLevel为1的单位直接挂到“所有单位”下
                    if (Common.GetIntValue(item["fdDepartmentLevel"]) == 1)
                    {
                        parentDetailItem.Items.Add(detailItem);
                    }
                    //fdDepartmentLevel大于1的单位，通过dic找到他的父单位，直接挂到父单位下
                    else
                    {
                        if (dic.ContainsKey(item["fdParentDepartmentId"].ToString()))
                        {
                            dic[item["fdParentDepartmentId"].ToString()].Items.Add(detailItem);
                        }
                        else
                        {
                            parentDetailItem.Items.Add(detailItem);
                            //单位层级有问题，找不到父亲单位
                        }
                    }
                    detailItem.UniqueName = itemUniqueName;

                    detailItem.Name = item["fdDepartmentName"].ToString();
                }

                if (date == string.Empty)
                {
                    continue;
                }
                //日数据长度为10，年数据长度为4，月数据长度为7
                else if (date.Length == 4)
                {
                    detailItem.DependantTotalYear = Common.GetIntValue(item["fdKeyId"]);
                    continue;
                }
                else if (date.Length == 10)
                {
                    detailItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    continue;
                }
                date = GetMonthByDate(date);
                //通过反射将数据填入相应的月数据属性中
                PropertyInfo pi = itemType.GetProperty("M" + date);
                pi.SetValue(detailItem, Common.GetIntValue(item["fdKeyId"]), null);
            }
            //2. 填入整改数
            foreach (var item in blockR.Rows)
            {
                string date = Common.GetStringValue(item["fdRiskDate"]);
                if (item["fdRiskDate"] != null && date.Trim() == string.Empty)
                {
                    continue;
                }
                //直接通过dic找到对应的记录
                string itemUniqueName = Common.GetStringValue(item["fdDepartmentId"]);
                if(!dic.ContainsKey(itemUniqueName))
                {
                    continue;
                }
                detailItem = dic[itemUniqueName];

                if (date == string.Empty)
                {
                    continue;
                }
                else if (date.Length == 4)
                {
                    detailItem.DependantTotalYear_Revise = Common.GetIntValue(item["fdKeyId"]);
                    continue;
                }

                date = GetMonthByDate(date);

                PropertyInfo pi_Revise = itemType.GetProperty("M" + date + "_Revise");
                pi_Revise.SetValue(detailItem, Common.GetIntValue(item["fdKeyId"]), null);
            }

            //将子节点里的数字汇总到父节点（“所有单位”节点）上
            ZMCA12DetailItem.SummarizedChildItemData(parentDetailItem);
        }
    }
}